package org.example.cake.interceptor;

import org.example.cake.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 文晓平
 * @version 1.0
 * @Description Jwt拦截
 * @date 2025/6/1 16:29
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            if (JwtUtil.isTokenValid(token)) {
                return true;
            }
//            if (JwtUtil.isTokenValid(token) && redisTemplate.hasKey(ProFixRedis.TOKEN+token)) {
//                return true;
//            }
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.getWriter().write("无效的 Token");
        return false;
    }
}
